//
//  QuotedSVGCViewController.m
//  Supervisor
//
//  Created by 小宇 on 2017/5/18.
//  Copyright © 2017年 北京怀教网络科技股份有限公司. All rights reserved.
//

#import "QuotedSVGCViewController.h"
#import "QuotedSVGCDetailViewController.h"
#import "SelectViewController.h"
#import "MyTableViewCell.h"
#import "ACAlertController.h"
#import "LZYSelectPhotoView.h"
#import "LZYSelectPhotoView.h"
#import "LZYDownLoaderView.h"
@interface QuotedSVGCViewController ()<UITableViewDelegate,UITableViewDataSource,ACEExpandableTableViewDelegate>{
    CGFloat _cellHeight[2];
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *cellTitles;
@property (nonatomic, strong) NSMutableArray *cellData;
@property (nonatomic, strong) NSMutableArray *fileList , *photos, *AllFiles;
@property (nonatomic, strong) SZTextView *meritsTextView;
@property (nonatomic, strong) SZTextView *suggestTextView;
@property (nonatomic, strong) LZYSelectPhotoView *mediaView;
@property (nonatomic, strong) LZYDownLoaderView *fileview;
@property (nonatomic, strong) UIView *downloadView;
@property (nonatomic, copy) NSString *schoolName,*crateDate,*meritsTextStr,*suggestTextStr;
@property (nonatomic, copy) NSString *orgid;
@property (nonatomic, strong)ACEExpandableTextCell *ACEcell;
@property (nonatomic, copy) NSString *jsoninfo;
@property (nonatomic, strong)UIButton *rightButton;
@property (nonatomic, assign) BOOL showPhoto;

@end

@implementation QuotedSVGCViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;
}

//找查到Nav底部的黑线
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BackgroundColor;
    self.extendedLayoutIncludesOpaqueBars=YES;
    [self add_tableView];
    [self addRightButton];
    self.cellData = [NSMutableArray arrayWithCapacity:2];
    [self.cellData addObject:[[NSAttributedString alloc] initWithData:[@"" dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]];[self.cellData addObject:[[NSAttributedString alloc] initWithData:[@"" dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]];
    if (self.quotedSVGCState == QuotedSVGCAdd) {
        self.navigationItem.title = @"添加督导过程";
        self.showPhoto = NO;
        self.fileList = nil;
        [self addFileWithFileArray:nil];
    }else{
        self.navigationItem.title = @"查看详情";
        [self getQuotedData];
    }
}

- (void)getQuotedData{
    NSDictionary *parameterDic = @{@"id":self.quotedSVId};
    [LZYNetworkHelper GET:procedureobj parameters:parameterDic success:^(id responseObject) {
        [self addFileWithFileArray:responseObject[@"files"]];
        self.mediaView.preShowMedias = self.photos;
        if (self.photos.count > 0) self.showPhoto = YES;
        self.orgid = [NSString stringWithFormat:@"%@",responseObject[@"procedure"][@"ddorg"]];
        self.crateDate = [responseObject[@"procedure"][@"createTime"] substringToIndex:10];
        [self.cellTitles replaceObjectAtIndex:0 withObject:[NSString stringWithFormat:@"督导学校：%@",responseObject[@"procedure"][@"ename"]]];
        [self.cellTitles replaceObjectAtIndex:1 withObject:[NSString stringWithFormat:@"督导日期：%@",[responseObject[@"procedure"][@"createTime"] substringToIndex:10]]];
        [self.cellData replaceObjectAtIndex:0 withObject:[[NSAttributedString alloc] initWithData:[responseObject[@"procedure"][@"plantxt"] dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:YES] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]];
        [self.cellData replaceObjectAtIndex:1 withObject:[[NSAttributedString alloc] initWithData:[[responseObject[@"procedure"][@"detail"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:YES] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        //[self.tableView showErrorPageView];
    } showHub:YES];
}

- (void)addFileWithFileArray:(NSArray *)fileArray{
    self.photos = [[NSMutableArray alloc]init];
    self.fileList = [[NSMutableArray alloc]init];
    for (int i = 0; i < fileArray.count; i++) {
        NSDictionary *filedic = fileArray[i];
        if ([filedic[@"filepath"] isImage]) {
            [self.photos addObject:filedic];
        }else{
            [self.fileList addObject:filedic];
        }
    }
    [self setTableFooterView];
}

- (void)setTableFooterView{
    BOOL hideDeleteButton;
    if (self.quotedSVGCState == QuotedSVGCDetail) {
        hideDeleteButton = YES;
    }else{
        hideDeleteButton = NO;
    }
    self.mediaView = [[LZYSelectPhotoView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 1)];
    self.mediaView.hideDeleteButton = hideDeleteButton;
    LZYWeakSelf(self)
    [self.mediaView observeViewHeight:^(CGFloat mediaHeight) {
        weakself.showPhoto = YES;
        weakself.mediaView.height = mediaHeight;
        [weakself layoutDownloadView];
        if ([[weakself.mediaView getAllPhotos] count] <= 0) {
            weakself.mediaView.height = [LZYSelectPhotoView defaultViewHeight];
            weakself.showPhoto = NO;
            [weakself.tableView reloadData];
        }
        [weakself.tableView reloadData];
    }];
    
    self.fileview = [[LZYDownLoaderView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, self.fileList.count > 0 ? 55 * self.fileList.count : 0) FilesList:self.fileList HideDeleteButton:hideDeleteButton];
    self.fileview.block = ^(CGFloat downLoaderViewHeight) {
        weakself.fileview.height = downLoaderViewHeight;
        [weakself layoutDownloadView];
        [weakself.tableView reloadData];
    };
    
    self.downloadView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width,self.fileview.height + self.mediaView.height)];
    self.downloadView.backgroundColor = [UIColor whiteColor];
    [self.downloadView addSubview:self.mediaView];
    [self.downloadView addSubview:self.fileview];
    self.tableView.tableFooterView = self.downloadView;
}

///重新布局collectionview
- (void)layoutDownloadView {
    CGFloat fileHeight = self.fileview.height > 10 ? self.fileview.height + 15 : self.fileview.height;
    self.downloadView.height = self.mediaView.height + fileHeight;
    if(_showPhoto == YES){
        self.fileview.top = self.mediaView.height + 15;
    }else{
        self.fileview.top = self.mediaView.height;
    }
    [self.downloadView addSubview:self.mediaView];
    [self.downloadView addSubview:self.fileview];
}


- (void)addRightButton{
    self.rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 28, 20.5)];
    if (self.quotedSVGCState == QuotedSVGCDetail) {
        [self.rightButton setTitle:@"编辑" forState:UIControlStateNormal];
    }else{
        [self.rightButton setTitle:@"保存" forState:UIControlStateNormal];
    }
    [self.rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.rightButton.titleLabel.font = AdaptedFontSize(12);
    [self.rightButton addTarget:self action:@selector(right_click:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    self.navigationItem.rightBarButtonItem = item;
}

- (NSMutableArray *)cellTitles{
    if (_cellTitles == nil) {
        _cellTitles = [NSMutableArray arrayWithArray:@[@"督导学校",@"请选择督导日期"]];
    }
    return _cellTitles;
}

- (void)add_tableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, Main_Screen_Width,self.view.frame.size.height) style:UITableViewStyleGrouped];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.mj_footer.automaticallyHidden = YES;
    self.tableView.backgroundColor = BackgroundColor;
    [self.view addSubview:self.tableView];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 2;
            break;
        case 1:
            return 1;
            break;
        case 2:
            return 1;
            break;
        default:
            return 1;
            break;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        if (indexPath.section == 0) {
            MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell"];
            if (cell == nil) {
                cell = [[NSBundle mainBundle]loadNibNamed:@"MyTableViewCell" owner:self options:nil][2];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            cell.leftTitleNameLabel.text = self.cellTitles[indexPath.row];
            if (self.quotedSVGCState == QuotedSVGCDetail) {
                cell.userInteractionEnabled = NO;
                cell.rightImgView.hidden = YES;
            }else{
                cell.userInteractionEnabled = YES;
            }
            return cell;
        }else if (indexPath.section == 1 || indexPath.section == 2){
            NSString *titleStr;
            if(indexPath.section == 1) titleStr = @"请填写督导计划及主要内容"; else titleStr = @"请填写督导过程记录";
            self.ACEcell = [tableView expandableTextCellWithId:@"plant"];
            if (self.cellData.count > 0) {
                self.ACEcell.text = _cellData[indexPath.section - 1];
            }
            self.ACEcell.textView.placeholder = titleStr;
            if(indexPath.section == 1) self.meritsTextView = self.ACEcell.textView; else self.suggestTextView = self.ACEcell.textView;
            self.ACEcell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (self.quotedSVGCState == QuotedSVGCDetail) {
                self.ACEcell.userInteractionEnabled = NO;
            }else{
                self.ACEcell.userInteractionEnabled = YES;
            }
            return self.ACEcell;
        }else{
            MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addFileCell"];
             if (cell == nil) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"MyTableViewCell" owner:self options:nil][3];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
             }
            if (self.showPhoto) {
                cell.rightImgView.hidden = YES;
                cell.rightLabel.text = @"继续添加";
            }else{
                cell.rightImgView.hidden = NO;
                cell.rightLabel.text = @"";
            }
            cell.leftTitleNameLabel.text = @"添加附件";
            if (self.quotedSVGCState == QuotedSVGCDetail) {
                cell.userInteractionEnabled = NO;
                cell.rightImgView.hidden = YES;
                cell.rightLabel.hidden = YES;
            }else{
                cell.userInteractionEnabled = YES;
            }
            return cell;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 50)];
        view.backgroundColor = [UIColor whiteColor];
        UIView *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, Main_Screen_Width - 30, 50) Text:@"督导计划及主要内容" TextColor:GeneralFontColor TextAlignment:NSTextAlignmentLeft Font:[UIFont systemFontOfSize:15] Target:nil Action:nil];
        [view addSubview:titleLabel];
        return view;
    }else if(section == 2){
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width - 30, 65)];
        view.backgroundColor = [UIColor whiteColor];
        UIView *lineview = [[UIView alloc]initWithFrame:CGRectMake(0, 14.5, Main_Screen_Width , 0.5)];
        lineview.backgroundColor = BackgroundColor;
        UIView *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 15, Main_Screen_Width - 30, 50) Text:@"督导过程记录" TextColor:GeneralFontColor TextAlignment:NSTextAlignmentLeft Font:[UIFont systemFontOfSize:15] Target:nil Action:nil];
        [view addSubview:lineview];
        [view addSubview:titleLabel];
        return view;
    }else if(section == 3){
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 15)];
        view.backgroundColor = [UIColor whiteColor];
        UIView *lineview = [[UIView alloc]initWithFrame:CGRectMake(0, 14.5, Main_Screen_Width , 0.5)];
        lineview.backgroundColor = BackgroundColor;
        [view addSubview:lineview];
        return view;
    }else{
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 50;
    }else if (section == 2){
        return 65;
    }else if (section == 3){
        return 15;
    }else{
        return 0.1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
            if (indexPath.row == 0) [self showSchoolWithCell:[self.tableView cellForRowAtIndexPath:indexPath]]; else [self showPickViewerWithCell:[self.tableView cellForRowAtIndexPath:indexPath]];
                break;
        case 1:

            break;
        case 3:
            [self addPhoto];
            break;
            
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 50;
    }else if(indexPath.section == 1 || indexPath.section == 2){
        return MAX(100, _cellHeight[indexPath.section - 1]);
    }else{
        return 50;
    }
}

- (void)tableView:(UITableView *)tableView updatedHeight:(CGFloat)height atIndexPath:(NSIndexPath *)indexPath
{
    _cellHeight[indexPath.section - 1] = height;
}

- (void)tableView:(UITableView *)tableView updatedText:(NSAttributedString *)text atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 || indexPath.section == 2) {
        [_cellData replaceObjectAtIndex:indexPath.section - 1 withObject:text];
    }
    
}

#pragma mark --- 日期选择
- (void)showPickViewerWithCell:(MyTableViewCell *)cell
{
    LZYDatePickerView *pickerView = [[LZYDatePickerView alloc] initDatePickerWithDefaultDate:nil
                                                                           andDatePickerMode:UIDatePickerModeDate];
    pickerView.LzyDatePicker = ^(NSString *dateString) {
        cell.leftTitleNameLabel.text = dateString;
        self.crateDate = dateString;
        [self.cellTitles replaceObjectAtIndex:1 withObject:dateString];
    };
    [pickerView show];
}

#pragma mark --- 学校选择
- (void)showSchoolWithCell:(MyTableViewCell *)cell
{
    SelectViewController *selectVC = [SelectViewController new];
    selectVC.navigationItem.title = @"选择督导学校";
    selectVC.LzySelectType = LZYSelectAloneChoice;
    selectVC.parameterDic = @{@"pa":@"c",@"type":@"1",@"themeId":@"0"};
    selectVC.url = getAll;
    LZYWeakSelf(self)
    selectVC.LzySelectAlone = ^(NSString *selectAloneString,NSString *selectAloneId) {
        weakself.orgid = selectAloneId;
        [self.cellTitles replaceObjectAtIndex:0 withObject:selectAloneString];
        NSIndexSet *indexset = [NSIndexSet indexSetWithIndex:0];
        [self.tableView reloadSections:indexset withRowAnimation:UITableViewRowAnimationFade];
    };
    [self.navigationController pushViewController:selectVC animated:YES];
}

- (void)addPhoto{
    ACAlertController *alert = [[ACAlertController alloc] initWithActionSheetTitles:@[@"相册", @"相机"] cancelTitle:@"取消"];
    [alert clickActionButton:^(NSInteger index) {
        if (index == 0) {
            [self.mediaView openAlbum];
        }else {
            [self.mediaView openCamera];
        }
    }];
    [alert show];
}

- (void)right_click:(UIButton *)sender{
    if (self.quotedSVGCState == QuotedSVGCDetail) {
        QuotedSVGCDetailViewController *vc = [[QuotedSVGCDetailViewController alloc]init];
        vc.quotedSVGCState = QuotedSVGCDetailEditD;
        vc.quotedSVId = self.quotedSVId;
        vc.LzyReloadData = ^(NSIndexPath *indexpath) {
            [self getQuotedData];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        //上传图片
        self.AllFiles = [[NSMutableArray alloc]init];
        //无本地图片时，直接进入上传
        if ([[self.mediaView getLocalPhotos] count] == 0) {
            if ([[self.mediaView getUrlPhotos] count] > 0) {
                NSMutableArray *photourlarr = [NSMutableArray arrayWithCapacity:[[self.mediaView getLocalPhotos] count]];
                for (LZYPhotoModel *model in [self.mediaView getUrlPhotos]) {
                    NSDictionary *dic = @{@"filepath":model.imageUrlString,@"filename":model.name};
                    [photourlarr addObject:dic];
                }
                [self.AllFiles addObjectsFromArray:photourlarr];
            }
            //pc端文件
            [self.fileview getDownLoadFileBlock:^(NSArray *downLoaderViewFiles) {
                self.fileList = [NSMutableArray arrayWithArray:downLoaderViewFiles];
                if (self.fileList.count > 0) {
                    [self.AllFiles addObjectsFromArray:self.fileList];
                }
                self.jsoninfo = [NSString arrayToJsonString:self.AllFiles];
                //上传基础数据
                [self submitDataWithJsonFileString:self.jsoninfo];
            }];
        }else{
            [LZYNetworkHelper uploadWithURL:uploads parameters:@{@"accessToken":[[User shareInstance]getUserAccessToken],@"filetype":@"3"} images:[self.mediaView getLocalPhotos] name:@"myfiles" fileName:@"FileData" mimeType:@"png" progress:^(NSProgress *progress) {
                [SVProgressHUD showProgress:progress.fractionCompleted status:@"正在上传"];
            } success:^(id responseObject) {
                if ([responseObject[@"code"] integerValue] == 1) {
                    [SVProgressHUD dismiss];
                    self.AllFiles = [[NSMutableArray alloc]init];
                    NSArray *arr = responseObject[@"obj"];
                    [self.AllFiles addObjectsFromArray:arr];
                    if ([[self.mediaView getUrlPhotos] count] > 0) {
                        NSMutableArray *photourlarr = [NSMutableArray arrayWithCapacity:[[self.mediaView getLocalPhotos] count]];
                        for (LZYPhotoModel *model in [self.mediaView getUrlPhotos]) {
                            NSDictionary *dic = @{@"filepath":model.imageUrlString,@"filename":model.name};
                            [photourlarr addObject:dic];
                        }
                        [self.AllFiles addObjectsFromArray:photourlarr];
                    }
                    //pc端文件
                    [self.fileview getDownLoadFileBlock:^(NSArray *downLoaderViewFiles) {
                        self.fileList = [NSMutableArray arrayWithArray:downLoaderViewFiles];
                        if (self.fileList.count > 0) {
                            [self.AllFiles addObjectsFromArray:self.fileList];
                        }
                        self.jsoninfo = [NSString arrayToJsonString:self.AllFiles];
                        //上传基础数据
                        [self submitDataWithJsonFileString:self.jsoninfo];
                    }];
                }
            } failure:^(NSError *error) {
                NSLog(@"%@",error);
            } showHub:YES];
        }
    }
}

- (void)submitDataWithJsonFileString:(NSString *)jsonFileString{
    if (![NSString isEmpty:self.orgid WithEmptyShowText:@"请选择督导学校"] && ![NSString isEmpty:self.crateDate WithEmptyShowText:@"请选择督导日期"]) {
        //判断类型
        LZYWeakSelf(self)
        if (self.quotedSVGCState == QuotedSVGCAdd) {
            NSDictionary *parametersDic = @{@"org.id":self.orgid,@"date":self.crateDate,@"plantxt":self.meritsTextView.text,@"detail":self.suggestTextView.text,@"filepath":jsonFileString};//字符串判空
            [LZYNetworkHelper POST:procedureadd parameters:parametersDic success:^(id responseObject) {
                if ([responseObject[@"code"] integerValue] == 1 ) {
                    [LZYShowMsg showText:@"记录上传成功"];
                    weakself.LzyReloadData(nil);
                    //刷新页面
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } failure:^(NSError *error) {
                [LZYShowMsg showText:@"记录上传失败"];
            } showHub:YES];
        }else{
            NSDictionary *parametersDic = @{@"id":self.quotedSVId,@"org.id":self.orgid,@"date":self.crateDate,@"plantxt":[self.meritsTextView.text stringByReplacingOccurrencesOfString:@"\U00002028" withString:@""],@"detail":[self.suggestTextView.text stringByReplacingOccurrencesOfString:@"\U00002028" withString:@""],@"filepath":jsonFileString};
            [LZYNetworkHelper POST:procedureedit parameters:parametersDic success:^(id responseObject) {
                if ([responseObject[@"code"] integerValue] == 1 ) {
                    [LZYShowMsg showText:@"记录修改成功"];
                    weakself.LzyReloadData(self.indexpath);
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } failure:^(NSError *error) {
                [LZYShowMsg showText:@"记录修改失败"];
            } showHub:YES];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
